package com.zhmsky.controller;

import com.zhmsky.model.ResultMap;
import org.apache.shiro.ShiroException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhmsky
 * @description 异常统一处理----使用 @RestControllerAdvice 注解可以全局捕获异常，这样controller中就可以省略大量的try-catch，
 *              再通过 ExceptionHandler来处理对应异常
 * @date 2021/12/5 19:40
 */
@RestControllerAdvice
public class ExceptionController {
    @Autowired
    private ResultMap resultMap;

    /**
     * @return
     * @description 处理shiro的异常
     */
    @ExceptionHandler(ShiroException.class)
    public ResultMap handle401() {
        return resultMap.fail().code(401).message("您没有权限访问！");
    }

    /**
     * @description 处理其他所有异常
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResultMap globalException(HttpServletRequest request, Throwable ex) {
        return resultMap.fail().code(getStatus(request).value()).message("访问出错,无法访问:" + ex.getMessage());
    }

    /**
     * @param request
     * @return
     * @description 获取请求状态码
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }


}
